package cn.tedu.egweibo5.base.exception;

import cn.tedu.egweibo5.base.response.JsonResult;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @Author: Miyako
 * @CreateTime: 2024-08-14  20:16
 * @Description: TODO
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler  {

    /**
     * @description:解决DTO类的元素不符合规则的异常
     * @author: Miyako
     * @param: [mEx]:捕获到异常
     * @return:异常的状态码与描述
     **/
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException mEx){
            String data = mEx.getFieldError().getDefaultMessage();
            return JsonResult.filed(data);
    }

    /**
     * @description:解决直接传参的元素不符合规则的异常
     * @author: Miyako
     * @param: [cEx] 捕获到异常
     * @return: 异常的状态码与描述
     **/
    @ExceptionHandler
    public  JsonResult doHandleConstraintViolationException  (ConstraintViolationException cEx){
        String data = cEx.getMessage().split(": ")[1].trim();
        return JsonResult.filed(data);
    }

    /**
     * @description:Json格式参数异常处理
     * @author: Miyako
     * @param: [mMEx]
     * @return: cn.tedu.egweibo5.base.response.JsonResult
     **/
    @ExceptionHandler
    public JsonResult doHandleMismatchedInputException (MismatchedInputException mMEx){
        return JsonResult.filed("Json文件格式错误");
    }




}
